package com.xxh.shirodemon.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxh.shirodemon.pojo.User;
import com.xxh.shirodemon.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;


import javax.annotation.Resource;

public class UserRealm extends AuthorizingRealm {

    @Resource
    UserService userService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


        //拿到登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();

        //设置（给与）用户的权限
        info.addStringPermission(currentUser.getPerm());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行认证");
        UsernamePasswordToken usertoken= (UsernamePasswordToken) token;
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //数据库中取得用户
        userQueryWrapper.eq("name",usertoken.getUsername());
        User user = userService.getOne(userQueryWrapper);
        //用户不存在
        if(user==null){//会抛出用户不存在异常
            return null;
        }
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);
        //密码可以加密 ：MD5 ，MD5加盐
        //密码认证不用做，shiro干
        //第一个参数，夹带私货（Principal），放入用户资源？方便授权的时候拿到？
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
